package com.bbcare.followup.plat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.bbcare.comm.*;
import com.bbcare.department.plat.service.impl.DepartmentBasicService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IFamilyReportService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;

import static com.bbcare.comm.Constants.GROWTH_REPORT;

/**
 * @desc 家庭监测报告数据控制类
 * @author tao
 *
 */
@Controller
@RequestMapping("/service/patient")
public class FamilyReportController {
    private final Log logger = LogFactory.getLog(FamilyReportController.class);

    @Autowired
    IFamilyReportService familyReportService;

    @Autowired
    private IPatientInfoHisService patientInfoHisService;

	@Autowired
	IPatientDAO patientdao;

    @Autowired
    private DepartmentBasicService departmentBasicService;

    @ResponseBody
    @RequestMapping("/oxygenPulserate/history")
    public QueryModel<Map<String, Object>> getOxygenPulserateList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getOxygenPulserateList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getQueueDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();

        paramMap.put("userId",userId);

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);

        List<Map<String, Object>> list= familyReportService.getOxygenPulserateHistory(paramMap);
        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	total= familyReportService.getOxygenPulserateHistoryCount(paramMap);
        }
		logger.info("out getOxygenPulserateList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    @ResponseBody
    @RequestMapping("/oxygenPulserate/historyByDay")
    public QueryModel<Map<String, Object>> getOxygenPulserateListByDay(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getOxygenPulserateList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getQueueDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();

        paramMap.put("userId",userId);
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);

        List<Map<String, Object>> list= familyReportService.getOxygenPulserateHistoryByDay(paramMap);
        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	total=familyReportService.getOxygenPulserateHistoryCountByDay(paramMap);
        }
		logger.info("out getOxygenPulserateList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    // 监测记录详情  按天为单位查询
    @ResponseBody
    @RequestMapping("/oxygenPulserate/detailByDay")
    public ResultModel<Map<String, Object>> getOxygenPulserateDetailByDay(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getFollowQueueList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getFollowQueueList----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
//        HttpSession session = request.getSession(true);
//        String authorId = (String) session.getAttribute("WEBUSER");
//        Object tenantId = session.getAttribute("tenantId");

        String userId = jsonData.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getOxygenPulserateDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户id不能为空");
        }

        String testTime = jsonData.getString("testTime");
        if(StringUtils.isEmpty(testTime)){
        	logger.debug("out getOxygenPulserateDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，监测日期不能为空");
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);

        paramMap.put("testTime",testTime);
        paramMap.put("userId", userId);
        Map<String, Object> retOut = familyReportService.getOxygenPulserateDetailByDay(paramMap);

        return new ResultModel<Map<String, Object>>(retOut);
    }


    // 队列信息List查询
    @ResponseBody
    @RequestMapping("/oxygenPulserate/detail")
    public ResultModel<Map<String, Object>> getOxygenPulserateDetail(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getFollowQueueList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getFollowQueueList----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
//        HttpSession session = request.getSession(true);
//        String authorId = (String) session.getAttribute("WEBUSER");
//        Object tenantId = session.getAttribute("tenantId");

        String oxygenPulserateId = jsonData.getString("oxygenPulserateId");
        if(StringUtils.isEmpty(oxygenPulserateId)){
        	logger.debug("out getOxygenPulserateDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，氧饱脉率ID不能为空");
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);

        paramMap.put("oxygenPulserateId", oxygenPulserateId);
        Map<String, Object> retOut = familyReportService.getOxygenPulserateDetailById(paramMap);

        return new ResultModel<Map<String, Object>>(retOut);
    }

    @ResponseBody
    @RequestMapping("/temperature/history")
    public QueryModel<Map<String, Object>> getBodytemperatureList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getBodytemperatureList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getQueueDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();

        paramMap.put("userId",userId);
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);

        List<Map<String, Object>> list= familyReportService.getBodytemperatureHistory(paramMap);
        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	total=familyReportService.getBodytemperatureHistoryCount(paramMap);
        }
		logger.info("out getBodytemperatureList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    // 体温记录详情查询
    @ResponseBody
    @RequestMapping("/temperature/detail")
    public ResultModel<Map<String, Object>> getBodytemperatureDetail(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getBodytemperatureDetail----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getBodytemperatureDetail----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
//        HttpSession session = request.getSession(true);
//        String authorId = (String) session.getAttribute("WEBUSER");
//        Object tenantId = session.getAttribute("tenantId");

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);

        String bodytemperatureId = jsonData.getString("bodytemperatureId");
        if(StringUtils.isEmpty(bodytemperatureId)){
        	logger.debug("out getBodytemperatureDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，体温记录ID不能为空");
        }

        paramMap.put("bodytemperatureId", bodytemperatureId);
        Map<String, Object> retOut = familyReportService.getBodytemperatureDetailById(paramMap);

        return new ResultModel<Map<String, Object>>(retOut);
    }

    // 患者主页监测数据统计 (氧饱脉率和体温异常统计)  先按科室队列下患者统计
    @ResponseBody
    @RequestMapping("/monitorDataStatistics")
    public ResultModel<Object> getMonitorDataStatistics(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getBodytemperatureDetail----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getBodytemperatureDetail----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id
//        String deptId = (String) sessionMap.get("rootGroupId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("type", jsonData.get("type"));

        List<Map<String, Object>> retOut = familyReportService.getMonitorDataStatistics(paramMap);

        return new ResultModel<Object>(retOut);
    }

    // 患者主页监测数据统计 (氧饱脉率和体温次数统计)  先按科室队列下患者统计
    @ResponseBody
    @RequestMapping("/monitorTimesStatistics")
    public ResultModel<Object> getMonitorTimesStatistics(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getMonitorTimesStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getBodytemperatureDetail----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("type", jsonData.get("type"));
        paramMap.put("flag", jsonData.get("flag"));
        List<Map<String, Object>> retOut = familyReportService.getmonitorTimesStatistics(paramMap);

        return new ResultModel<Object>(retOut);
    }

    // 检测数据列表  检测患者统计数据
    @ResponseBody
    @RequestMapping("/familyreport/patientDataStatistics")
    public ResultModel<Object> getPatientDataStatistics(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getPatientDataStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getPatientDataStatistics----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id
//        String deptId = (String) sessionMap.get("rootGroupId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("type", jsonData.get("type")); //1:体温 2 氧饱脉率 3 气质 4 其他

        Map<String, Object> retOut = familyReportService.getpatientsStatistics(paramMap);

        return new ResultModel<Object>(retOut);
    }

    @ResponseBody
    @RequestMapping("/oxygenPulserate/patientListqry")
    public QueryModel<Map<String, Object>> getOxygenPulseratePatientList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getOxygenPulseratePatientList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id
        paramMap.put("tenantId",tenantId);
        paramMap.put("authorId",authorId);

        List<Map<String, Object>> list= familyReportService.getOxygenPulseratePatientList(paramMap);
        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	total = familyReportService.getOxygenPulseratePatientCount(paramMap);
        }

		logger.info("out getOxygenPulseratePatientList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    @ResponseBody
    @RequestMapping("/bodyTemperature/patientListqry")
    public QueryModel<Map<String, Object>> getBodytemperaturePatientList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getBodytemperaturePatientList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id
        paramMap.put("tenantId",tenantId);
        paramMap.put("authorId",authorId);

        List<Map<String, Object>> list= familyReportService.getBodyTemperaturePatientList(paramMap);
        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	total = familyReportService.getBodyTemperaturePatientCount(paramMap);
        }
		logger.info("out getOxygenPulseratePatientList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    @ResponseBody
    @RequestMapping("/growth/patientListqry")
    public QueryModel<Map<String, Object>> getGrowthPatientList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getGrowthPatientList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 创建人
        paramMap.put("tenantId",tenantId);
        paramMap.put("authorId",authorId);

        paramMap.put("appSourceType",Constants.PT_USER_INFO_DEFAULT_TENANT_ID);//加上患者app自己录入的数据
        List<Map<String, Object>> list= familyReportService.getGrowthPatientList(paramMap);
        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	total = familyReportService.getGrowthPatientCount(paramMap);
        }
		logger.info("out getGrowthPatientList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    @ResponseBody
    @RequestMapping("/growth/history")
    public QueryModel<Map<String, Object>> getGrowthListByUserId(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getBodytemperatureList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getQueueDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.putAll(requestParam);
        paramMap.put("tenantId",tenantId);
        paramMap.put("userId",userId);
        paramMap.put("appSourceType",Constants.PT_USER_INFO_DEFAULT_TENANT_ID);//加上患者app自己录入的数据
        List<Map<String, Object>> list= familyReportService.getGrowthHistory(paramMap);
        int total= 0;
        /*if(!CollectionUtils.isEmpty(list)){
        	familyReportService.getGrowthPatientCount(paramMap);
        }*/
//        int total= familyReportService.getBodytemperatureHistoryCount(paramMap);
		logger.info("out getBodytemperatureList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    // 生长发育详情查询
    @ResponseBody
    @RequestMapping("/growth/getGrowthInfo")
    public ResultModel<Map<String, Object>> getGrowthDetail(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getGrowthDetail----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthDetail----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
//        HttpSession session = request.getSession(true);
//        String authorId = (String) session.getAttribute("WEBUSER");
//        Object tenantId = session.getAttribute("tenantId");

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String doctorName = (String) sessionMap.get("authorName");// 租户id
        String deptId = (String) sessionMap.get("deptId");//科室ID
        paramMap.put("tenantId",tenantId);
        paramMap.put("deptId",deptId);
        paramMap.put("doctorName",doctorName);


        //增加 	年龄计算类型	曲线类型	标志
        String ageType =  jsonData.getString("ageType");
        String scoreType =  jsonData.getString("scoreType");
        //如果为空则传入默认值
        if(StringUtils.isEmpty(ageType)){
        	ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        }else{
        	if(!Constants.GROWTH_AGE_TYPE_CORRECT.equals(ageType) && !Constants.GROWTH_AGE_TYPE_ACTUAL.equals(ageType)){
        		ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        	}
        }
        if(StringUtils.isEmpty(scoreType)){
        	scoreType = Constants.GROWTH_SCORE_PERCENT;
        }else{
        	if(!Constants.GROWTH_SCORE_PERCENT.equals(scoreType) && !Constants.GROWTH_SCORE_ZSCORE.equals(scoreType)){
        		scoreType = Constants.GROWTH_SCORE_PERCENT;
        	}
        }

        paramMap.put("ageType", ageType);
        paramMap.put("scoreType", scoreType);

        paramMap.put("appSourceType",Constants.PT_USER_INFO_DEFAULT_TENANT_ID);//加上患者app自己录入的数据
        String growthRecordId = jsonData.getString("growthRecordId");
        if(StringUtils.isEmpty(growthRecordId)){
        	logger.debug("out getGrowthDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，生长发育评估记录ID不能为空");
        }

        paramMap.put("growthRecordId", growthRecordId);
        Map<String, Object> retOut = familyReportService.getGrowthDeatail(paramMap);

        return new ResultModel<Map<String, Object>>(retOut);
    }

    // 生长发育详情删除
    @ResponseBody
    @RequestMapping("/growth/delGrowthRecord")
    public ResultModel<Map<String, Object>> delGrowthRecord(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in delGrowthRecord----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthDetail----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String doctorName = (String) sessionMap.get("authorName");// 租户id
        String deptId = (String) sessionMap.get("deptId");//科室ID
        paramMap.put("tenantId",tenantId);
        paramMap.put("deptId",deptId);
        paramMap.put("doctorName",doctorName);

        String recordId = jsonData.getString("recordId");
        if(StringUtils.isEmpty(recordId)){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，生长发育评估记录ID不能为空");
        }
         familyReportService.deleteGrowthRecordById(recordId);
        return new ResultModel("success");
    }

    // 根据生长发育记录 查询生长发育详情
    @ResponseBody
    @RequestMapping("/growth/getGrowthCurvedata")
    public ResultModel<Map<String, Object>> getGrowthCurvedata(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getGrowthCurvedata----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthDetail----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        String growthRecordId = jsonData.getString("growthRecordId");
        if(StringUtils.isEmpty(growthRecordId)){
        	logger.debug("out getGrowthDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，生长发育评估记录ID不能为空");
        }

        String userId = jsonData.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getGrowthDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }

        //增加 	年龄计算类型	曲线类型	标志
        String ageType =  jsonData.getString("ageType");
        String scoreType =  jsonData.getString("scoreType");

        //如果为空则传入默认值
        if(StringUtils.isEmpty(ageType)){
        	ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        }else{
        	if(!Constants.GROWTH_AGE_TYPE_CORRECT.equals(ageType) && !Constants.GROWTH_AGE_TYPE_ACTUAL.equals(ageType)){
        		ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        	}
        }
        if(StringUtils.isEmpty(scoreType)){
        	scoreType = Constants.GROWTH_SCORE_PERCENT;
        }else{
        	if(!Constants.GROWTH_SCORE_PERCENT.equals(scoreType) && !Constants.GROWTH_SCORE_ZSCORE.equals(scoreType)){
        		scoreType = Constants.GROWTH_SCORE_PERCENT;
        	}
        }

        paramMap.put("ageType", ageType);
        paramMap.put("scoreType", scoreType);

        paramMap.put("growthRecordId", growthRecordId);
        paramMap.put("userId", userId);
        paramMap.put("tenantId", tenantId);

        paramMap.put("appSourceType",Constants.PT_USER_INFO_DEFAULT_TENANT_ID);//加上患者app自己录入的数据

        Map<String, Object> retOut = familyReportService.getGrowthCurvedata(paramMap);
        logger.info("out getGrowthCurvedata----arg=="+retOut);
        return new ResultModel<Map<String, Object>>(retOut);
    }

    // 根据体重、身高、头围  --生长发育详情查询
	@ResponseBody
    @RequestMapping("/growth/getGrowthCurvedataByValue")
    public ResultModel<Map<String, Object>> getGrowthCurvedataByValue(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getGrowthCurvedataByValue----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthCurvedataByValue----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        String type = jsonData.getString("type");
        if(StringUtils.isEmpty(type)){
        	logger.debug("out getGrowthCurvedataByValue----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，type不能为空");
        }

        String values = jsonData.getString("values");
        if(StringUtils.isEmpty(values)){
        	logger.debug("out getGrowthCurvedataByValue----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，values不能为空");
        }

        String userId = jsonData.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getGrowthCurvedataByValue----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }

        String testTime = jsonData.getString("testTime");
        if(StringUtils.isEmpty(testTime)){
        	logger.debug("out getGrowthCurvedataByValue----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，监测时间不能为空");
        }

        try{
        	DateUtil.getDate_8(testTime);
        }catch(Exception e){
        	logger.debug("out getGrowthCurvedataByValue----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，监测时间格式不正确");
        }

        String scoreType =  jsonData.getString("scoreType");
        if(StringUtils.isEmpty(scoreType)){
        	scoreType = Constants.GROWTH_SCORE_PERCENT;
        }else{
        	if(!Constants.GROWTH_SCORE_PERCENT.equals(scoreType) && !Constants.GROWTH_SCORE_ZSCORE.equals(scoreType)){
        		scoreType = Constants.GROWTH_SCORE_PERCENT;
        	}
        }
        jsonData.put("scoreType", scoreType);

        jsonData.put("tenantId", tenantId);
        Map<String, Object> retOut = familyReportService.getGrowthCurvedata(jsonData);
        logger.info("out getGrowthCurvedataByValue----arg=="+retOut);
        return new ResultModel<Map<String, Object>>(retOut);
    }


    // 生长发育记录添加
    @ResponseBody
    @RequestMapping("/growth/addGrowthRecord")
    public ResultModel<Map<String, Object>> addGrowthRecord(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in addGrowthRecord----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in addGrowthRecord----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
        Map<String, Object> session = ToolUtils.getSessionInfo(request);
        String authorId = (String) session.get("authorId");
        String tenantId = (String) session.get("tenantId");
        String authorName = (String) session.get("authorName");

        String userId = jsonData.getString("userId");
		String weight = jsonData.getString("weight");
		String height = jsonData.getString("height");
        Date testTime = jsonData.getDate("testTime");
        if (testTime == null) {
            testTime = new Date();
        }
        String headCircumference = jsonData.getString("headCircumference");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out addGrowthRecord----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户ID不能为空");
        }
//        if(StringUtils.isEmpty(weight)){
//        	logger.debug("out addGrowthRecord----arg== null");
//        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，体重不能为空");
//        }
//        if(StringUtils.isEmpty(height)){
//        	logger.debug("out getGrowthDetail----arg== null");
//        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，身高不能为空");
//        }
//        if(StringUtils.isEmpty(headCircumference)){
//        	logger.debug("out addGrowthRecord----arg== null");
//        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，头围不能为空");
//        }

        jsonData.put("authorId",authorId);
        jsonData.put("tenantId",tenantId);
//        jsonData.put("authorName",authorName);

        Map<String,Object> userMap = new HashMap<String,Object>();
        userMap.put("userId", userId);
        userMap.put("tenantId", tenantId);
        Patient pt = patientdao.selectById(userMap);

        String birthday ="";
        if(!org.springframework.util.StringUtils.isEmpty(pt.getBirthday())){
            birthday =pt.getBirthday().toString();
        }

        String pregnancyDay = "";
        if(org.springframework.util.StringUtils.isEmpty(pt.getPregnancyDay())){
            pregnancyDay = "280";
        }else{
            pregnancyDay = String.valueOf(pt.getPregnancyDay());
        }
        int ageMonth = 0;
        // 5岁 按每月30天 整月估算  5*12=60

        Long birthLong=ToolUtils.getCorrect(birthday,Integer.parseInt(pregnancyDay));//生日时间戳
        ageMonth=(int)((testTime.getTime()-birthLong)/(1000*60*60*24)/30.4);
        if (ageMonth > 60){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_GROWTHS_STANDARD_WHO_AGE_OVER_MAXAGE, "该用户年龄不在评测范围内！");
        }

        jsonData.put("remark","随访系统新增生长发育数据");
        Map<String, Object> retOut = familyReportService.addGrowthRecord(jsonData);
        // 生长发育保存成功后推送问卷id到小程序
        // type=6 生长发育新增推送
        String growId = (String) retOut.get("id");
        int type = GROWTH_REPORT;
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String deptId = (String) sessionMap.get("deptId");// 租户id
        String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
        JSONObject map =new JSONObject();
        map.put("type",type);
        map.put("growId",growId);
        map.put("platType",Integer.parseInt(platType));
        map.put("deptId",deptId);
        if (StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl"))) {
            //如果config.properties中有redirectUrl配置项，才会发送请求。没有配置项，就不发送了。
            HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl"), map.toJSONString());
        }

		try{
			if(!StringUtils.isEmpty(userId)){
				if(null != pt){
					Map<String,Object> paramRecord = new HashMap<String,Object>();
					paramRecord.putAll(jsonData);
					paramRecord.put("opUsertype",Constants.OPCODE_TYPE_DOCTOR);
					paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
					paramRecord.put("authorId",authorId);
					paramRecord.put("userId",userId);
		            String remark = "医生【"+authorName+"】为患者【" + pt.getUserName() + "】录入生长发育监测数据";
		            paramRecord.put("remark", remark);
		            paramRecord.put("updateAccept",SeqUtil.getSeqNo());
		            paramRecord.put("opCode",Constants.OP_CODE_1011);
					patientInfoHisService.saveOperationRecord(paramRecord);
				}
			}

		}catch(Exception e){
			logger.error("保存上传生长发育操作记录表报错", e);
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, e.getMessage());
		}

        return new ResultModel<Map<String, Object>>(retOut);
    }

    // 计算生长发育百分比
    @ResponseBody
    @RequestMapping("/growth/getGrowthPercentiles")
    public ResultModel<Map<String, Object>> getGrowthPercentiles(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getGrowthPercentiles----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthPercentiles----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
        Map<String, Object> session = ToolUtils.getSessionInfo(request);
        String authorId = (String) session.get("authorId");
        String tenantId = (String) session.get("tenantId");

        String userId = jsonData.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getGrowthPercentiles----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户ID不能为空");
        }

        String type = jsonData.getString("type");
        if(StringUtils.isEmpty(type)){
        	logger.debug("out getGrowthPercentiles----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，type不能为空");
        }

        String values = jsonData.getString("values");
        if(StringUtils.isEmpty(values)){
        	logger.debug("out getGrowthPercentiles----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，values不能为空");
        }

        String testTime = jsonData.getString("testTime");
        if(StringUtils.isEmpty(testTime)){
        	logger.debug("out getGrowthPercentiles----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，监测时间不能为空");
        }
        try{
        	DateUtil.getDate_8(testTime);
        }catch(Exception e){
        	logger.debug("out getGrowthPercentiles----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，监测时间格式不正确");
        }

        jsonData.put("authorId",authorId);
        jsonData.put("tenantId",tenantId);
        String ageType = null;
        //2022年04月06日 西交大按照实际年龄计算
        if(tenantId.equals("xaefynewJCEBta001")){
            ageType = Constants.GROWTH_AGE_TYPE_ACTUAL;
        }
        Map<String, Object> retOut = familyReportService.getGrowthPercentiles(jsonData,ageType,null);
        logger.warn("out getGrowthPercentiles----arg=="+retOut);
        return new ResultModel<Map<String, Object>>(retOut);
    }

    //查询最近一次生长发育记录
    @ResponseBody
    @RequestMapping("/growth/getLastGrowth")
    public ResultModel<Map<String, Object>> getLastGrowth(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getLastGrowth----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthPercentiles----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
        Map<String, Object> session = ToolUtils.getSessionInfo(request);
        String authorId = (String) session.get("authorId");
        String tenantId = (String) session.get("tenantId");

        String userId = jsonData.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getGrowthPercentiles----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户ID不能为空");
        }

        jsonData.put("authorId",authorId);
        jsonData.put("tenantId",tenantId);
        Map<String, Object> retOut = familyReportService.getlastGrowth(jsonData);
        logger.info("out getLastGrowth----arg=="+retOut);
        return new ResultModel<Map<String, Object>>(retOut);
    }

    /**
     * 计算出生体格P值。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/growth/getPercentiles")
    public ResultModel<Map<String, Object>> getBirthPercentiles(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in getBirthPercentiles----arg==" + arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getBirthPercentiles----no data node...");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        final String type = jsonData.getString("type");
        if(StringUtils.isEmpty(type)){
            logger.debug("out getBirthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，type不能为空");
        }

        final String gender = jsonData.getString("gender");
        if(StringUtils.isEmpty(gender)){
            logger.debug("out getBirthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，gender不能为空");
        }

        final String value  = jsonData.getString("value");
        if(StringUtils.isEmpty(value)){
            logger.debug("out getBirthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，value不能为空");
        }

        final String age    = jsonData.getString("age");
        if(StringUtils.isEmpty(age)){
            logger.debug("out getBirthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，age不能为空");
        }

        final String pweek  = jsonData.getString("pweek");
        if(StringUtils.isEmpty(pweek)){
            logger.debug("out getBirthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，pweek（孕周）不能为空");
        }
        final String pday   = jsonData.getString("pday");
        if(StringUtils.isEmpty(pday)){
            logger.debug("out getBirthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，pday（孕周/天）不能为空");
        }

        Map<String, Object> retOut = familyReportService.getPercentiles(jsonData);
        logger.warn("out getBirthPercentiles----arg=="+retOut);
        return new ResultModel<Map<String, Object>>(retOut);
    }

    @ResponseBody
    @PostMapping("/queryBirthPercentile")
    public ResultModel<Map> queryBirthWeightPercentiles(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryBirthWeightPercentiles()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String babyGender = jsonData.getString("gender");
        if (StringUtils.isBlank(babyGender)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入gender性别或值为空！"));
        }
        if (!babyGender.equalsIgnoreCase("N") && !babyGender.equalsIgnoreCase("F")) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入gender性别格式错误，只能是N男或F女！"));
        }

        final String weightG    = jsonData.getString("weight");
        final String lengthCM   = jsonData.getString("length");
        final String headCM     = jsonData.getString("head");
        if (StringUtils.isBlank(weightG) && StringUtils.isBlank(lengthCM) && StringUtils.isBlank(headCM)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入weight体重(单位g)、length身长(单位cm)、head头围(单位cm)或值为空！"));
        }

        Double dWeightKg    = 0.0;
        Double dLengthCm    = 0.0;
        Double dHeadCm      = 0.0;

        if (StringUtils.isNotBlank(weightG)) {
            try {
                dWeightKg = Double.parseDouble(weightG) / 1000;
            } catch (NumberFormatException nfe) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，weight体重(单位g)格式错误！"));
            }
        }
        if (StringUtils.isNotBlank(lengthCM)) {
            try {
                dLengthCm = Double.parseDouble(lengthCM);
            } catch (NumberFormatException nfe) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，length身长(单位cm)格式错误！"));
            }
        }
        if (StringUtils.isNotBlank(headCM)) {
            try {
                dHeadCm = Double.parseDouble(headCM);
            } catch (NumberFormatException nfe) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，head头围(单位cm)格式错误！"));
            }
        }

        Map<String,Object> paraMap  = new HashMap<>();
        if (dWeightKg != 0.0 ) {
            paraMap.put("weightValue", dWeightKg);
        }
        if (dLengthCm != 0.0 ) {
            paraMap.put("lengthValue", dLengthCm);
        }
        if (dHeadCm != 0.0 ) {
            paraMap.put("headValue", dHeadCm);
        }
        paraMap.put("gender", babyGender);
        Map<String,Object> retMap   = familyReportService.getBirthPercentiles(paraMap);
        return new ResultModel(retMap);
    }

}
